package riteh.eventNetwork.client;


import com.google.gson.Gson;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;

public class ActivityHome extends ListActivity {
	
	private ListView list;
	private HomeEventsAdapter listAdapter;
	private String events[][];
	private long userId;
	private Intent intentNotifications, intentSettings, intentAbout;
	
	private String circles[][];
	private boolean selCircles[];
	private int numOfSelCircles = 0;
	
	private String priorities[] = {"Urgent","Important","Irrelevant"};
	private boolean selPriorities[] = {true, true, true};
	private int numOfSelPriorities = 3;

/* ********************** OVERRIDE FUNCTIONS ******************************/
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(C.TAG, "HOME Activity");
		setContentView(R.layout.home);
		
		userId = this.getIntent().getExtras().getLong("userId");
		intentNotifications = new Intent(this, ActivityNotifications.class);
		intentNotifications.putExtra("userId", userId);
        intentSettings = new Intent(this, ActivitySettings.class);
        intentAbout = new Intent(this, ActivityAbout.class);

		refresh();
		
		list = getListView();
		registerForContextMenu(list);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.home, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId	()) {
		case R.id.homeMenuFilterCircles:
			filterCircles();
			return true;
		case R.id.homeMenuFilterPriorities:
			filterPriorities();
			return true;
		case R.id.homeMenuSettings:
			showSettings();
			return true;
		case R.id.homeMenuRefresh:
			refresh();
			return true;
		case R.id.homeMenuAbout:
			startActivity(intentAbout);
			return true;
		}
		return false;
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.long_click_home_event, menu);
	}
	
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		View v = info.targetView;
		long selectionId = v.getId();
		switch(item.getItemId()) {
		case R.id.longClickHomeEventRespond:
			homeEventRespond(selectionId);
			return true;
		case R.id.longClickHomeEventUsers:
			homeEventUsers(selectionId);
			return true;
		}
		return false;
	}
	
/* ********************** PRIVATE FUNCTIONS *******************************/
	   
	private void refresh() {
		int numOfNotifications;
		numOfNotifications = getNumberOfNotifications();
		
		if (numOfNotifications > 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("You have " + numOfNotifications + " new notifications!")
			       .setCancelable(false)
			       .setPositiveButton("Show", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   startActivity(intentNotifications);
			           }
			       })
			       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
		
		getCircles();
		getHomeEvents();
	}
	
    private int getNumberOfNotifications() {
    	Log.d(C.TAG, "TABS: getNumberOfNotification()");
    	
    	RestClient client = new RestClient(getString(R.string.serverMethodGetNumberOfNotifications));
    	client.AddParam("userId", String.valueOf(userId));
    	
    	String result = C.getMethod0(client, getString(R.string.serverMethodGetNumberOfNotifications));
    	if (C.resultSuccess(this, result, getString(R.string.toastGetNumberOfNotificationsError))) {
    		return Integer.parseInt(result);
    	}
    	else return 0;
    }
	
	private void filterPriorities() {
    	Log.d(C.TAG, "HOME: filterPriorities()");
    	
		final CharSequence[] items = new CharSequence[3];
		items[0] = "Urgent";
		items[1] = "Important";
		items[2] = "Irrelevant";
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select priorities for event filtering: ");
		builder.setMultiChoiceItems(items, selPriorities,  new OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				selPriorities[which] = isChecked;
				if (isChecked) numOfSelPriorities++;
				else numOfSelPriorities--;
			}
		});
		
		
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	private void filterCircles() {
    	Log.d(C.TAG, "HOME: filterCircles()");
    	
		final CharSequence[] items;
		
		items = new CharSequence[circles.length];
		for (int i=0; i<circles.length; i++) {
			items[i] = circles[i][1];
		}
				
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select from circles for events filtering: ");
		builder.setMultiChoiceItems(items, selCircles,  new OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				selCircles[which] = isChecked;
				if (isChecked) numOfSelCircles++;
				else numOfSelCircles--;
			}
		});
		
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	private void getCircles() {
		Log.d(C.TAG,"HOME: getCircles()");
		
    	RestClient client = new RestClient(getString(R.string.serverMethodGetCircles));
    	client.AddParam("userId", String.valueOf(userId));
    	
    	String result[][] = C.getMethod2(client, getString(R.string.serverMethodGetCircles));
    	
    	if (C.resultSuccess(this, result, getString(R.string.toastGetCirclesError))) {
    		
    		// TODO
    		if (selCircles != null) {
    			if (selCircles.length == result.length) {
        			return;
    			}
    		}
    		
			selCircles = new boolean[result.length];
    		circles = new String[result.length][3];
    		circles = result;
    		numOfSelCircles = circles.length;
    		for (int i=0; i<circles.length; i++) {
    			selCircles[i] = true;
    		}
    	}
	}
	
	private void showSettings() {
		 startActivity(intentSettings);
	}
	
	private void homeEventRespond (long eventId) {
		Log.d(C.TAG, "HOME: homeEventRespond()");

		RestClient client = new RestClient(getString(R.string.serverMethodRespondToEvent));
		client.AddParam("userId", String.valueOf(userId));
		client.AddParam("eventId", String.valueOf(eventId));
		String result = C.getMethod0(client, getString(R.string.serverMethodRespondToEvent));
		
		if (C.resultSuccess(this, result, getString(R.string.toastRespondToEventError))) {
			C.toast(this, "Respond successfull!", 0);
			refresh();
		}
		
	}
	
	private void homeEventUsers(long eventId) {
		Log.d(C.TAG, "HOME: homeEventUsers()");

		RestClient client = new RestClient(getString(R.string.serverMethodUsersWhoResponded));
		client.AddParam("eventId", String.valueOf(eventId));
		String result[][] = C.getMethod2(client, getString(R.string.serverMethodUsersWhoResponded));
		
		if (C.resultSuccess(this, result, getString(R.string.toastUsersWhoRespondedError))) {

			if (result[0][0].compareTo("0") == 0) return;

			final CharSequence[] items = new CharSequence[result.length];
			
			for (int i=0; i<result.length; i++) {
				items[i] = result[i][1] + " " + result[i][2];
			}
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Users who responded:");
			builder.setItems(items, null);
			AlertDialog alert = builder.create();
			alert.show();
		}
	}
	
	private void getHomeEvents() {	
		Log.d(C.TAG, "HOME: getHomeEvents()");
		
		if (circles == null || circles.length == 0) {
			C.toast(this, "You have no circles!");
			return;
		}
		
		// Find circles for filtering
		String listOfCircles[] = new String[numOfSelCircles];
		int tmp=0;
		for (int i=0; i<circles.length; i++) {
			if (selCircles[i]) {
				listOfCircles[tmp] = circles[i][0];
				//Log.d(C.TAG,"listOfCircles[]=" + listOfCircles[tmp]);
				tmp++;
			}
		}
		
		// Find priorities for filtering
		String listOfPriorities[] = new String[numOfSelPriorities];
		tmp=0;
		for (int i=0; i<priorities.length; i++) {
			if (selPriorities[i]) {
				listOfPriorities[tmp] = priorities[i];
				tmp++;
			}
		}
				
		RestClient client = new RestClient(getString(R.string.serverMethodGetHomeEvents));
		Gson gson = new Gson();
		
		client.AddParam("userId", String.valueOf(userId));
		client.AddParam("listOfCircles", gson.toJson(listOfCircles));
		client.AddParam("priorities", gson.toJson(listOfPriorities));
		String result[][] = C.getMethod2(client, getString(R.string.serverMethodGetHomeEvents));
		
		if (C.resultSuccess(this, result, getString(R.string.toastGetHomeEventsError))) {
			if (result[0][0].compareTo("0") == 0) events = new String[0][0];
			else {
				events = new String[result.length][6];
				events = result;
				listAdapter = new HomeEventsAdapter(this, events);
				setListAdapter(listAdapter);
			}
		}
		
	}
	
	private class HomeEventsAdapter extends ArrayAdapter<String[]> {
		private final Activity context;
		private final String[][] events;

		public HomeEventsAdapter(Activity context, String[][] events) {
			super(context, R.layout.home_list, events);
			this.context = context;
			this.events = events;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View rowView = inflater.inflate(R.layout.home_list, null, true);
			
			TextView title = (TextView) rowView.findViewById(R.id.homeListTitle);
			TextView user = (TextView) rowView.findViewById(R.id.homeListUser);
			TextView duration = (TextView) rowView.findViewById(R.id.homeListDuration);
			TextView responses = (TextView) rowView.findViewById(R.id.homeListResponses);
			TextView priority = (TextView) rowView.findViewById(R.id.homeListPriority);

			rowView.setId(Integer.parseInt(events[position][0]));
			user.setText(events[position][1]);
			title.setText(events[position][2]);
			duration.setText(events[position][3]);
			priority.setText(events[position][4]);
			responses.setText(events[position][5]);

			return rowView;
		}
	}
	
}
